package com.hadoop.wordcount;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.NLineInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

//运行命令： ~/hadoop-2.7.2/bin/hadoop jar hadoop-example-0.0.1-SNAPSHOT.jar com.hadoop.wordcount.WordCount5 /hadoop/inputdata/wordcount/ /hadoop/outputdata/wordcount/
public class WordCount5 {

	public static class WordMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
		Text word = new Text();
		IntWritable one = new IntWritable(1);

		@Override
		public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
			StringTokenizer tokenizer = new StringTokenizer(value.toString());

			while (tokenizer.hasMoreTokens()) {
				word.set(tokenizer.nextToken());
				context.write(word, one);
			}
		}
	}

	public static class WordReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

		@Override
		public void reduce(Text key, Iterable<IntWritable> values, Context context)
				throws IOException, InterruptedException {
			int sum = 0;
			for (IntWritable count : values) {
				sum += count.get();
			}
			context.write(key, new IntWritable(sum));
		}
	}

	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		// TODO Auto-generated method stub

		//hdfs://192.168.12.15:9000
		//Path outPutPath=new Path("/hadoop/outputdata/wordcount/");
		Path outPutPath=new Path(args[1]);
		Configuration conf=new Configuration();
		FileSystem fs=FileSystem.get(conf);
		if(fs.exists(outPutPath)) {
			fs.delete(outPutPath, true);
		}
		fs.close();//关闭文件流
		
		Job job=Job.getInstance(conf, "word count");
		job.setJarByClass(WordCount5.class);
		job.setMapperClass(WordMapper.class);
		job.setReducerClass(WordReducer.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		//job.setNumReduceTasks(2);
		//hdfs://192.168.12.15:9000
		//FileInputFormat.addInputPath(job, new Path("/hadoop/inputdata/wordcount/"));
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, outPutPath);
		//NLineInputFormat.setNumLinesPerSplit(job, 20);
		
		System.out.println(job.waitForCompletion(true)?0:1);
	}

}
